<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="900px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="事件编号" prop="emergencyCode">
            <el-input v-model="formData.emergencyCode" placeholder="请输入事件编号" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="水库名称" prop="reservoirName">
            <el-select v-model="formData.reservoirName" placeholder="请选择水库" :disabled="isView" style="width: 100%">
              <el-option label="东圳水库" value="东圳水库" />
              <el-option label="金钟水库" value="金钟水库" />
              <el-option label="西音水库" value="西音水库" />
              <el-option label="山美水库" value="山美水库" />
              <el-option label="惠女水库" value="惠女水库" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="应急类型" prop="emergencyType">
            <el-select v-model="formData.emergencyType" placeholder="请选择应急类型" :disabled="isView" style="width: 100%">
              <el-option label="防洪应急" value="flood" />
              <el-option label="大坝安全" value="dam-safety" />
              <el-option label="供水应急" value="water-supply" />
              <el-option label="地质灾害" value="geological" />
              <el-option label="设备故障" value="equipment" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="紧急程度" prop="urgencyLevel">
            <el-select v-model="formData.urgencyLevel" placeholder="请选择紧急程度" :disabled="isView" style="width: 100%">
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发生时间" prop="occurTime">
            <el-date-picker
              v-model="formData.occurTime"
              type="datetime"
              placeholder="请选择发生时间"
              :disabled="isView"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="应急状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" :disabled="isView" style="width: 100%">
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已处理" value="completed" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="处理人员" prop="handler">
            <el-input v-model="formData.handler" placeholder="请输入处理人员姓名" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入联系电话" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="响应时间" prop="responseTime">
            <el-input-number
              v-model="formData.responseTime"
              placeholder="请输入响应时间"
              :disabled="isView"
              :min="0"
              :precision="0"
              style="width: 100%"
            />
            <span style="margin-left: 8px; color: #909399;">分钟</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="影响范围" prop="affectedArea">
            <el-input v-model="formData.affectedArea" placeholder="请输入影响范围" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经济损失" prop="economicLoss">
            <el-input-number
              v-model="formData.economicLoss"
              placeholder="请输入经济损失"
              :disabled="isView"
              :min="0"
              :precision="2"
              style="width: 100%"
            />
            <span style="margin-left: 8px; color: #909399;">万元</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="人员伤亡" prop="casualties">
            <el-input v-model="formData.casualties" placeholder="请输入人员伤亡情况" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="事件描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请详细描述应急事件的具体情况"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="应急措施" prop="measures">
        <el-input
          v-model="formData.measures"
          type="textarea"
          :rows="3"
          placeholder="请输入已采取或计划采取的应急措施"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="处理结果" prop="result">
        <el-input
          v-model="formData.result"
          type="textarea"
          :rows="3"
          placeholder="请输入处理结果"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="经验教训" prop="lessons">
        <el-input
          v-model="formData.lessons"
          type="textarea"
          :rows="2"
          placeholder="请输入经验教训和改进建议"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
          :disabled="isView"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'

// Props
interface Props {
  modelValue: boolean
  title: string
  emergencyData?: any
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '新增应急事件',
  emergencyData: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// 模拟API接口
const saveEmergency = async (data: any) => {
  // 模拟保存
  return { code: 200, msg: '保存成功' }
}

const updateEmergency = async (data: any) => {
  // 模拟更新
  return { code: 200, msg: '更新成功' }
}

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  id: null,
  emergencyCode: '',
  reservoirName: '',
  emergencyType: '',
  urgencyLevel: '',
  occurTime: '',
  status: 'pending',
  handler: '',
  phone: '',
  responseTime: null,
  affectedArea: '',
  economicLoss: null,
  casualties: '',
  description: '',
  measures: '',
  result: '',
  lessons: '',
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  emergencyCode: [
    { required: true, message: '请输入事件编号', trigger: 'blur' }
  ],
  reservoirName: [
    { required: true, message: '请选择水库名称', trigger: 'change' }
  ],
  emergencyType: [
    { required: true, message: '请选择应急类型', trigger: 'change' }
  ],
  urgencyLevel: [
    { required: true, message: '请选择紧急程度', trigger: 'change' }
  ],
  occurTime: [
    { required: true, message: '请选择发生时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择应急状态', trigger: 'change' }
  ],
  handler: [
    { required: true, message: '请输入处理人员姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入事件描述', trigger: 'blur' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => props.emergencyData && props.emergencyData.id)
const isView = computed(() => props.title.includes('查看'))

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    emergencyCode: '',
    reservoirName: '',
    emergencyType: '',
    urgencyLevel: '',
    occurTime: '',
    status: 'pending',
    handler: '',
    phone: '',
    responseTime: null,
    affectedArea: '',
    economicLoss: null,
    casualties: '',
    description: '',
    measures: '',
    result: '',
    lessons: '',
    remark: ''
  })
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 初始化表单数据
const initFormData = () => {
  if (props.emergencyData) {
    Object.assign(formData, props.emergencyData)
  } else {
    resetForm()
  }
}

// 监听弹窗显示
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      initFormData()
    }
  }
)

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    const submitData = { ...formData }
    
    if (isEdit.value) {
      await updateEmergency(submitData)
      ElMessage.success('更新成功')
    } else {
      await saveEmergency(submitData)
      ElMessage.success('保存成功')
    }

    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== false) { // 排除表单验证失败的情况
      ElMessage.error('提交失败')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>